﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace AppGPS.Helper
{
    class ImageConvert
    {
        public static BitmapImage base64image(string base64string)
        {
            byte[] fileBytes = Convert.FromBase64String(base64string);

            using (MemoryStream ms = new MemoryStream(fileBytes, 0, fileBytes.Length))
            {
                ms.Write(fileBytes, 0, fileBytes.Length);
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.SetSource(ms);
                return bitmapImage;
            }
        }
        public static string ImageToBase64(Image image1)
        {
            Stream photoStream = ImageToStream(image1);
            BitmapImage bimg = new BitmapImage();
            bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo

            byte[] bytearray = null;
            using (MemoryStream ms = new MemoryStream())
            {
                WriteableBitmap wbitmp = new WriteableBitmap(bimg);
                wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
                bytearray = ms.ToArray();
            }
            string str = Convert.ToBase64String(bytearray);

            return str;
        }
        public static string BitmapImageToBase64(BitmapImage bimg)
        {
            byte[] bytearray = null;
            using (MemoryStream ms = new MemoryStream())
            {
                WriteableBitmap wbitmp = new WriteableBitmap(bimg);
                wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
                bytearray = ms.ToArray();
            }
            string str = Convert.ToBase64String(bytearray);

            return str;
        }
        public static string BitmapImageToBase64(BitmapImage bimg,int width,int height)
        {
            byte[] bytearray = null;
            using (MemoryStream ms = new MemoryStream())
            {
                WriteableBitmap wbitmp = new WriteableBitmap(bimg);
                wbitmp.SaveJpeg(ms, width, height, 0, 100);
                bytearray = ms.ToArray();
            }
            string str = Convert.ToBase64String(bytearray);

            return str;
        }
        private static Stream ImageToStream(Image image1)
        {
            WriteableBitmap wb = new WriteableBitmap(400, 400);

            wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });

            wb.Invalidate();
            Stream myStream = new MemoryStream();

            wb.SaveJpeg(myStream, 400, 400, 0, 70);

            return myStream;
        }
    }
}
